//
//  XKOAuthViewController.swift
//  XK2WeiBo
//
//  Created by 陈肖坤 on 2017/6/30.
//  Copyright © 2017年 陈肖坤. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD
import AFNetworking


class XKOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //MARK: - 设置试图
    private func setupUI() {
    view.backgroundColor = UIColor.white
        setupNav()
    }
    
    //MARK: - 设置导航
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(XKOAuthViewController.cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.plain, target: self, action: #selector(XKOAuthViewController.autoFillClick))
        navigationItem.title = "OAuth登陆"
    }
    
    //MARK: - 监听事件
    @objc private func cancelClick() {
    dismiss(animated: true, completion: nil)
    }
    @objc private func autoFillClick() {
    let jsString = "document.getElementById('userId').value='17777868553',document.getElementById('passwd').value='xia0cuicui,'"
        //js注入
        webView.evaluateJavaScript(jsString)
    }

    //MARK: - 懒加载控件
    private lazy var webView:WKWebView = {
        let view = WKWebView()
        view.navigationDelegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APP_KEY)&redirect_uri=\(REDIRECT_URI)")!
//        print(url)
//        let request = NSURLRequest(url: url as URL) as URLRequest
        view.load(NSURLRequest(url: url as URL) as URLRequest)
        return view
    }()
    
}
extension XKOAuthViewController: WKNavigationDelegate {
    //开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show()
    }
    //加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
    }
    //将要加载request
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let urlString = navigationAction.request.url?.absoluteString
        //hasPrefix前缀
        if let u = urlString , u.hasPrefix(REDIRECT_URI) {
            let query = navigationAction.request.url?.query
            if let q = query {
                let code = q.substring(from: "code=".endIndex)
                loadUserAccount(code: code)
            }
        }
        //decisionHandler韩德楼
        decisionHandler(WKNavigationActionPolicy.allow)
        
        
    }
    
}

extension XKOAuthViewController {
    func loadUserAccount(code:String) {
        
        XKNetworkTool.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
            // 判断请求回来的res 是否有值 而且 是否可以转成一个字典
            // 如果在在判断可选值是否有值 可以转成你想要的类型 一般情况下 as?
            print("成功:\(String(describing: response))")
                print("返回的数据不是一个字典")
            // 字典转模型
        }) { (error) -> () in
            print(error)
        }
        
    }
    
//    let urlString = "https://api.weibo.com/oauth2/access_token"
//       let params = [
//        "client_id":APP_KEY,
//        "client_secret":APP_SECRET,
//        "grant_type":"authorization_code",
//        "code":code,
//        "redirect_uri":REDIRECT_URI
//        ]
//        print(code)
//        let manager = AFHTTPSessionManager()
//        //添加“text/plain”
//        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        manager.post(urlString, parameters: params, progress: nil, success: { (_, response) in
//            print("成功:\(String(describing: response))")
//        }) { (_, Error) in
//            print("失败:\(Error)")
//            SVProgressHUD.displayDuration(for: "请求失败")
//        }
//    }
}




